import areaData from './area.js'
import { ElCascader } from 'element-plus'
import { h, defineComponent, defineProps, watchEffect } from 'vue'

let citys = Object.keys(areaData.city_list).map(k => {
    return { code: parseInt(k), label: areaData.city_list[k] };
});
let counties = Object.keys(areaData.county_list).map(k => {
    return { code: parseInt(k), label: areaData.county_list[k] };
});
let provinces = Object.keys(areaData.province_list).map(k => {
    let v1 = areaData.province_list[k];
    let item1 = { value: v1, label: v1 };
    let kmin = parseInt(k);
    let kmax = kmin + 10000;
    item1.children = citys.filter(p1 => p1.code > kmin && p1.code < kmax).map(p1 => {
        let item2 = { value: p1.label, label: p1.label };
        let kmax2 = p1.code + 100;
        item2.children = counties.filter(p2 => p2.code > p1.code && p2.code < kmax2).map(p2 => {
            return { value: p2.label, label: p2.label }
        })
        return item2;
    })

    return item1;
});


export default defineComponent({
    name: "MySelectArea",
    inheritAttrs: true,
    extends: ElCascader,
    props:{
        province:[String,Array]
    },
    data(){
        return {
            _optionsData:[]
        }
    },
    watch:{
        province:{
            handler(){
                if(this.province){
                    if(typeof(this.province)=="string"){
                        this._optionsData = provinces.filter(p=>p.value==this.province);        
                    }else{
                        this._optionsData = provinces.filter(p=>this.province.indexOf(p.value)!=-1);    
                    }
                }else{
                    this._optionsData = provinces;
                }
            },
            immediate:true
        }
    },
    render() {
        let props = {
            ...this.$attrs, ...this.$props, options: this._optionsData,
            modelValue: (this.modelValue?this.modelValue.split("/"):[]),
            'onUpdate:modelValue': value => {
                this.$emit('update:modelValue', value.join("/"));
            }
        }
        props.clearable = true;
        return h(ElCascader, props, this.$slots);
    }
});